package com.eagle.roomcrawler.urlmanager;

import com.eagle.roomcrawler.crawlerdata.HttpExecute;
import com.eagle.roomcrawler.entity.Url;
import com.eagle.roomcrawler.mapper.UrlMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * URL管理器
 */
@Service
public class UrlManager {

    @Autowired
    private UrlMapper urlMapper;
    @Autowired
    private HttpExecute httpExecute;

    public final static LinkedBlockingQueue<String> configUrls = new LinkedBlockingQueue<String>(50000);//用户配置的URL任务队列
    public final static LinkedBlockingQueue<String> crawlerUrls = new LinkedBlockingQueue<String>(50000);//需要抓取的URL队列
    public static void main(String[] args){
       String url = "http://zu.sz.fang.com";
       pushUrlToQueue(url,"CONFIG");
        try {
//            httpExecute.crawlerThread();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将url放到任务队列
     * @param url
     * @param kind
     */
    public static void pushUrlToQueue(String url,String kind){
        //  offer方法在添加元素时，如果发现队列已满无法添加的话，会直接返回false。
        if(kind.equals("CONFIG")){//存放到配置URL任务队列
            configUrls.offer(url);
        }else{
            crawlerUrls.offer(url);
        }
    }

    /**
     * 配置url，添加任务
     * @param url
     */
    public String configUrl(Url url){
        String urlStr = url.getUrlName();
        url = urlMapper.findOne(url.getUrlName());
        if(url != null){//该url已经存在数据库中
            if(url.getUrlStatus().equals("1")){//1是URL可用，2是不可用
                pushUrlToQueue(url.getUrlName(),"CONFIG");
                try {
                    HttpExecute.crawlerUrl();
                    httpExecute.crawlerThread(url.getUrlName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return "ENABLED";
            }else{
                return "DISABLED";
            }
        }else{//数据库中没有该URL
            pushUrlToQueue(urlStr,"CONFIG");
            url = new Url();
            url.setUrlName(urlStr);
            url.setUrlStatus("1");//默认为可用
            urlMapper.insert(url);
            String result = "";
            try {
                result = HttpExecute.crawlerUrl();
//                result = "2";
                if(result.equals("2")){//不可用
                    url.setUrlStatus(result);
                    urlMapper.update(url);
                    return "DISABLED";
                }else{
                    httpExecute.crawlerThread(urlStr);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return "EXCEPTION";
            }
            return "ENABLED";
        }
    }

//    public String updateUrl(Url url){
//        urlMapper.
//    }
}
